package com.beimin.evedata.hsqldb;

import java.util.Map;
import java.util.Map.Entry;

import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.pretty.DDLFormatter;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

public abstract class HibUtils {
	@SuppressWarnings("unchecked")
	public static void printContextDatabaseSchemas(AbstractApplicationContext ac) {
		Map<String, LocalSessionFactoryBean> beansOfType = ac.getBeansOfType(LocalSessionFactoryBean.class);
		for (Entry<String, LocalSessionFactoryBean> entry : beansOfType.entrySet()) {
			String name = entry.getKey();
			LocalSessionFactoryBean sessionFactory = entry.getValue();
			System.out.println("-- sessionFactory " + name.substring(1) + " tables:");
			printDatabaseSchema(sessionFactory);
		}
	}

	public static void printDatabaseSchema(LocalSessionFactoryBean sessionFactory) {
		Configuration cfg = sessionFactory.getConfiguration();
		printConfigurationSchema(cfg);
	}

	public static void printConfigurationSchema(Configuration cfg) {
		String[] createSQLs = cfg.generateSchemaCreationScript(new MySQLDialect());
		for (String createSQL : createSQLs) {
			System.out.print(new DDLFormatter(createSQL).format());
			System.out.println(";");
		}
		String newline = System.getProperty("line.separator");
		System.out.println(newline + newline);
	}
}
